<style scoped>

</style>
<template>
    <div>
        <div class="top-title bg-white">
            <div class="top-title-text text-18 black blod">电子围栏管理</div>
        </div>
        <div class="page-content flex-column" style="height: calc(100% - 50px);">
            <div class="search-block bg-white p-20">
                <Form inline :label-width="90">
                    <!--<FormItem label="名称/编码">-->
                        <!--<Input v-model="search.str" class="w240" type="text" placeholder="请输入名称或编码"/>-->
                    <!--</FormItem>-->
                    <!--<FormItem label=" " :label-width="20">-->
                    <!--<Select v-model="search.progress" class="w160"placeholder="方案" clearable>-->
                    <!--<Option value="1">已制定方案</Option>-->
                    <!--<Option value="2">未制定方案</Option>-->
                    <!--</Select>-->
                    <!--</FormItem>-->
                    <!--<FormItem :label-width="0">-->
                        <!--<Button @click="goSearch" class="m-r-10" type="primary">搜索</Button>-->
                        <!--<Button @click="reset">重置</Button>-->
                    <!--</FormItem>-->
                    <FormItem :label-width="0">
                        <Button v-show="!editing" @click="addPolygon" class="m-r-10" type="primary"><img src="assets/image/add.png">新增围栏</Button>
                        <Button v-show="editing" @click="finishEdit" class="m-r-10" type="success">完成围栏区域编辑</Button>
                    </FormItem>
                </Form>
            </div>

            <div class="content-block bg-white p-0-20 flex-1 flex-column">

                <div id="mainContent" class="flex-1-height">
                    <div id="mapBox" style="width:100%;height:98%"></div>
                </div>

            </div>
        </div>

        <Modal v-model="itemModal"
               :title="itemData.id? '编辑围栏': '新增围栏'"
               class-name="vertical-center-modal"
               width="800"
               :mask-closable="false"
        >
            <div class="p-l-20">
                <div class="top-title-text text-18 black blod">基础信息</div>
                <div class="p-15-0 max-h500">
                    <Form label-position="top">

                        <Row>
                            <Col span="11">
                                <FormItem label="围栏名称" required>
                                    <Input v-model="itemData.wl_mc" class="w240" type="text" placeholder="请输入"/>
                                </FormItem>
                            </Col>
                            <Col span="2" style="text-align: center"></Col>
                            <Col span="11">
                                <FormItem label="负责人" required>
                                    <Select v-model="itemData.wl_fzr" class="w240"placeholder="请选择" filterable clearable transfer>
                                        <Option v-for="(item,i) in userList"
                                                :key="i"
                                                :value="item.user_name"
                                        >{{item.user_name}}-{{item.phone_num}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>

                        <!--<Row>-->
                            <!--<Col span="11">-->
                                <!--<FormItem label="考勤开始时间" required>-->
                                    <!--<Input v-model="itemData.sz_wz" class="w240" type="text" placeholder="请输入"/>-->
                                <!--</FormItem>-->
                            <!--</Col>-->
                            <!--<Col span="2" style="text-align: center"></Col>-->
                            <!--<Col span="11">-->
                                <!--<FormItem label="考勤结束时间" required>-->
                                    <!--<Input v-model="itemData.mh" class="w240" type="text" placeholder="请输入"/>-->
                                <!--</FormItem>-->
                            <!--</Col>-->
                        <!--</Row>-->

                        <!--<Row>-->
                            <!--<Col span="11">-->
                                <!--<FormItem label="提醒类型" required>-->
                                    <!--<RadioGroup v-model="itemData.a">-->
                                        <!--<Radio label="出围栏"></Radio>-->
                                        <!--<Radio label="进围栏"></Radio>-->
                                        <!--<Radio label="进围栏"></Radio>-->
                                    <!--</RadioGroup>-->
                                <!--</FormItem>-->
                            <!--</Col>-->
                            <!--<Col span="2" style="text-align: center"></Col>-->
                            <!--<Col span="11">-->
                                <!--<FormItem label="提醒频率" required>-->
                                    <!--<RadioGroup v-model="itemData.a">-->
                                        <!--<Radio label="每天"></Radio>-->
                                        <!--<Radio label="工作日"></Radio>-->
                                        <!--<Radio label="周末"></Radio>-->
                                    <!--</RadioGroup>-->
                                <!--</FormItem>-->
                            <!--</Col>-->
                        <!--</Row>-->

                        <FormItem label="坐标点" required>
                            <Input :value="itemData.wl_zbd && JSON.stringify(itemData.wl_zbd)" readonly type="textarea"
                                   :rows="4" class="flex-1"></Input>
                        </FormItem>
                        <Button @click="editPolygon" class="m-r-10" type="primary">编辑坐标点</Button>

                    </Form>

                </div>
            </div>

            <div slot="footer">
                <Button @click="cancel" class="m-r-10">取消</Button>
                <Button v-show="itemData.id" @click="delItem" class="m-r-10" type="error">删除围栏</Button>
                <Button @click="confirm" type="primary">确定</Button>
            </div>
        </Modal>

    </div>
</template>

<script>

    var map
    var mouseTool
    var polyEditor


    // opts.strokeColor string (default #00D3FC)	线条颜色，使用16进制颜色代码赋值。默认值为#00D3FC
    // opts.strokeOpacity number (default 0.9)	轮廓线透明度，取值范围 [0,1] ，0表示完全透明，1表示不透明。默认为0.9
    // opts.strokeWeight number (default 2)	轮廓线宽度
    // opts.fillColor string (default #00B2D5)	多边形填充颜色，使用16进制颜色代码赋值，如：#00B2D5
    // opts.fillOpacity number (default 0.5)	多边形填充透明度，取值范围 [0,1] ，0表示完全透明，1表示不透明。默认为0.5

    let defaultOpt = {
        strokeColor: "#55f",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillColor: '#1791fc',
        fillOpacity: 0.6,
        strokeStyle: "solid",
        cursor: 'pointer',
    };

    let editOpt = {
        strokeColor: "#1791fc",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillColor: '#ff5555',
        fillOpacity: 0.6,
        strokeStyle: "solid",
        cursor: 'pointer',
    };


    export default {
        data() {
            return {
                type: '考勤区域',

                search: {
                    str: '',
                    timeArr: [],
                },
                total: 0,
                page: 1,
                pageSize: 10,

                userList: [],

                tableHeight: 500,
                columns: [
                    {
                        title: '门禁名称',
                        key: 'mj_mc',
                    },
                    {
                        title: '门禁编码',
                        key: 'mj_bh'
                    },
                    {
                        title: '所在位置',
                        key: 'sz_wz'
                    },
                    {
                        title: '门号',
                        key: 'mh'
                    },
                    {
                        title: '管理员',
                        key: 'gly',
                        // sortable: 'custom'
                    },
                    {
                        title: '联系方式',
                        key: 'lxfs',
                        // sortable: 'custom'
                    },
                    {
                        title: '操作',
                        render: (h, params) => {
                            let look = h('a', {
                                class: 'm-r-10',
                                on: {
                                    click: () => {
                                        console.log('查看', params.row);
                                        this.$router.push({
                                            path: `/iotManage/doorDetail?type=${this.type}&id=${params.row.id}`
                                        })
                                    }
                                }
                            }, '查看');
                            let edit = h('a', {
                                class: 'm-r-10',
                                on: {
                                    click: () => {
                                        console.log('编辑', params.row);
                                        this.editItem(params.row);
                                    }
                                }
                            }, '编辑');
                            let del = h('a', {
                                class: 'red m-r-10',
                                on: {
                                    click: () => {
                                        console.log('删除', params.row);

                                        this.$Modal.confirm({
                                            title: '提示',
                                            content: '<p>确认删除吗？</p>',
                                            onOk: () => {
                                                let postData = {
                                                    mjId: params.row.id
                                                };

                                                this.util.post('/hand/deleteMj', postData, 'formdata').then(res => {
                                                    if (res.status == 200) {
                                                        this.$Message.success(res.msg);
                                                        this.getList();
                                                    } else {
                                                        this.$Message.warning(res.msg)
                                                    }
                                                })
                                            },
                                        });
                                    }
                                }
                            }, '删除');
                            return h('div', [look, edit, del]);
                        }
                    },
                ],
                list: [],

                itemModal: false,
                itemData: {
                    "wl_mc":"",
                    "wl_fzr":"",
                    "wl_zbd":"",
                },

                currentPolygon: '',

                editing: false,

                userList: [],
            }
        },
        created() {
            this.getUserList();
        },
        mounted() {
            let mainContent = document.getElementById('mainContent')
            if (mainContent) {
                this.tableHeight = mainContent.offsetHeight - 40
            }
            this.timer = setInterval(() => {
                if (mainContent) {
                    this.tableHeight = mainContent.offsetHeight - 40
                } else {
                    mainContent = document.getElementById('mainContent')
                }
            }, 1000)


            this.initMap()

        },
        beforeDestroy() {
            clearInterval(this.timer);
        },
        methods: {
            getUserList() {

                let postData = {
                    // orId: this.detailId,
                };
                this.util.get('/hand/userAccountLists', postData).then(res => {
                    console.log('获取机构人员', JSON.parse(JSON.stringify(res)))
                    res.data && res.data.forEach(v => {
                        v.state = v.status === 'T'
                    })
                    this.userList = res.data || []
                })
            },

            initMap() {


                map = new AMap.Map("mapBox", {
                    center: [111.006536,35.026872],
                    zoom: 14,
                    doubleClickZoom: false,
                });

                mouseTool = new AMap.MouseTool(map)

                mouseTool.on('draw', this.handleDraw)

                setTimeout(() => {
                    this.getList();
                }, 1000)


            },

            addPolygon() {
                mouseTool.polygon({
                    strokeColor: "#00f",
                    strokeOpacity: 1,
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillColor: '#1791fc',
                    fillOpacity: 0.4,
                    // 线样式还支持 'dashed'
                    strokeStyle: "solid",
                    // strokeStyle是dashed时有效
                    // strokeDasharray: [30,10],
                })
            },

            handleDraw(e) {
                console.log('绘制完成', e);

                let type = e.obj.type
                console.log(type)

                let path = e.obj.getPath()
                console.log('path', path)

                if(path.length > 2) {
                    mouseTool.close();
                    this.handleAddPolygon(e.obj)
                }

            },
            handleAddPolygon(polygon) {
                console.log('添加的多边形', polygon)
                this.currentPolygon = polygon;
                this.currentPolygon.setOptions({
                    ...editOpt
                })

                this.itemData =  {
                    wl_mc: '',
                    wl_fzr: '',
                    wl_zbd: polygon.getPath().map(v => {
                        return {
                            longitude: v.lng,
                            latitude: v.lat,
                        }
                    }),
                }

                // console.log('this.itemData.path', this.itemData.path)
                console.log('多边形path', JSON.stringify(this.itemData.path))

                this.itemModal = true;

            },


            goSearch() {
                this.onPageChange(1)
            },
            reset() {
                this.search = {
                    str: '',
                    timeArr: [],
                };
                this.goSearch();
            },
            getList() {
                map.clearMap();

                let postData = {

                };


                this.util.get('/hand/wlLists', postData).then(res => {
                    console.log('获取围栏列表', JSON.parse(JSON.stringify(res)))
                    this.list = res.data || [];
                    this.total = res.total || 0;

                    // let list = [
                    //     {
                    //         wl_mc: '考勤1',
                    //         wl_zbd: [[116.35764,39.904834],[116.341933,39.890611],[116.367425,39.876911],[116.378583,39.889557]]
                    //     },
                    //     {
                    //         wl_mc: '考勤2',
                    //         wl_zbd: [[116.411387,39.88334],[116.421086,39.89638],[116.436964,39.880376],[116.424519,39.874712]]
                    //     },
                    // ];

                    this.list.forEach(v => {
                        try{
                            v.wl_zbd = JSON.parse(v.wl_zbd)
                            if(Array.isArray(v.wl_zbd)) {
                                //有可能是两种形式，数组的或对象的
                                if(v.wl_zbd) {

                                }

                                this.createPolygon(v);
                            }
                        }catch(err) {
                            // console.log('绘制错误', err);
                        }
                    })

                })






            },
            createPolygon(item) {

                if(!item.wl_zbd) {
                    return;
                }

                var polygon = new AMap.Polygon({
                    path: item.wl_zbd.map(v => {
                        return [v.longitude || v[0], v.latitude || v[1]]
                    }),
                    ...defaultOpt
                });

                let lnglat = polygon.getBounds().getCenter()
                // console.log('中心', [lnglat.lng,lnglat.lat])


                var text = new AMap.Text({
                    text:item.wl_mc,
                    anchor:'center', // 设置文本标记锚点
                    style:{
                        'text-align': 'center',
                        'font-size': '20px',
                        'color': 'white',
                        'background-color': 'transparent',
                        'border-width': 0,

                        // 'padding': '.75rem 1.25rem',
                        // 'margin-bottom': '1rem',
                        // 'border-radius': '.25rem',
                        // 'background-color': 'white',
                        // 'width': '15rem',
                        // 'border-width': 0,
                        // 'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                        'text-align': 'center',
                        'font-size': '20px',
                        'color': 'white'
                    },
                    position: [lnglat.lng,lnglat.lat],
                });

                polygon.Data = item;
                polygon.Text = text;
                item.polygon = polygon;

                polygon.on('dblclick', this.handleEditPolygon);


                map.add([polygon, text])
                map.setFitView();

            },
            handleEditPolygon(e) {
                console.log('双击', e);
                let polygon = e.target;

                if(polygon.Data) {


                    if(this.currentPolygon) {
                        this.currentPolygon.setOptions({
                            ...defaultOpt
                        })
                    }

                    this.currentPolygon = polygon;
                    this.currentPolygon.setOptions({
                        ...editOpt
                    })

                    // polyEditor = new AMap.PolygonEditor(map, this.currentPolygon);
                    // polyEditor.open();
                    // this.editing = true;
                    this.itemData = polygon.Data;
                    this.itemModal = true;

                }


            },

            editItem(itemData) {

                this.itemData = {
                    id: itemData.id,
                    "mj_mc": itemData.mj_mc,
                    "mj_bh": itemData.mj_bh,
                    "sz_wz": itemData.sz_wz,
                    "mh": itemData.mh,
                    "lxfs": itemData.lxfs,
                    "ms": itemData.ms,
                    "gly": itemData.gly,
                };
                this.itemModal = true;
            },
            cancel() {
                this.itemModal = false;
            },

            finishEdit() {
                this.editing = false;
                this.itemModal = true;

                console.log('polyEditor', polyEditor)
                let path = polyEditor.editingPolyObj.poly.getPath()
                console.log('path', path);
                console.log('path2', JSON.parse(JSON.stringify(path)));
                this.itemData.wl_zbd = path.map(v => {
                    return {
                        longitude: v.lng,
                        latitude: v.lat,
                    }
                });
                polyEditor.close();

            },
            editPolygon() {
                this.editing = true;
                this.itemModal = false;
                polyEditor = new AMap.PolygonEditor(map, this.currentPolygon);
                polyEditor.open();
            },

            delItem() {

                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确认删除吗？</p>',
                    onOk: () => {
                        let postData = {
                            wl_id: this.itemData.id
                        };

                        this.util.post('/hand/deleteDzwl', postData, 'formdata').then(res => {
                            if (res.status == 200) {
                                this.$Message.success(res.msg);
                                this.getList();
                                this.itemModal = false;
                            } else {
                                this.$Message.warning(res.msg)
                            }
                        })
                    },
                });
            },


            confirm() {

                let itemData = this.itemData;

                if (!itemData.wl_mc) {
                    this.$Message.warning('请输入围栏名称');
                    return;
                }
                if (!itemData.wl_fzr) {
                    this.$Message.warning('请选择负责人');
                    return;
                }

                let postData = {
                    "wl_mc": itemData.wl_mc,
                    "wl_fzr": itemData.wl_fzr,
                    "wl_zbd": JSON.stringify(itemData.wl_zbd),
                };

                let url = '/hand/addDzwl';
                if (itemData.id) {
                    postData.id = itemData.id;
                    url = '/hand/addDzwl';
                }

                this.util.post(url, postData).then(res => {
                    if (res.status == 200) {
                        this.$Message.success(res.msg);
                        this.getList();
                        this.itemModal = false;
                    } else {
                        this.$Message.warning(res.msg)
                    }
                })

            },

        },
    }
</script>

